import { channelsType } from '@/store/reducer/channels';

type authType = {
  token: string;
  refresh_token: string;
};
const TOKEN_KEY = 'geek-park-h5-token';
// 存token
export const setAuth = (auth: authType) => {
  localStorage.setItem(TOKEN_KEY, JSON.stringify(auth));
};
//取token
export const getAuth = (): authType => {
  return JSON.parse(localStorage.getItem(TOKEN_KEY) || '{}');
};
// 删除token
export const removeAuth = () => {
  localStorage.removeItem(TOKEN_KEY);
};
// 判断是否有token
export const hasToken = () => {
  if (getAuth().token) {
    return true;
  } else {
    return false;
  }
};

const CHANNEL_KEY = 'itcast-geek-park-channel';
/**
 * 保存频道数据到本地
 * @param {*} channels
 */
export const setLocalChannels = (channels: channelsType[]) => {
  localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels));
};

/**
 * 获取本地的频道数据，如果没有数据，使用时注意空数组的判断
 * @returns
 */
export const getLocalChannels = () => {
  return JSON.parse(localStorage.getItem(CHANNEL_KEY) || '[]') as channelsType[];
};

/**
 * 删除本地的频道数据
 */
export const removeLocalChannels = () => {
  localStorage.removeItem(CHANNEL_KEY);
};

// 搜索关键字的本地缓存键名
const SEARCH_HIS_KEY = 'itcast_history';

/**
 * 从缓存获取搜索历史关键字
 */
export const getLocalHistories = (): string[] => {
  return JSON.parse(localStorage.getItem(SEARCH_HIS_KEY) || '[]');
};

/**
 * 将搜索历史关键字存入本地缓存
 * @param {Array} histories
 */
export const setLocalHistories = (histories: string[]) => {
  localStorage.setItem(SEARCH_HIS_KEY, JSON.stringify(histories));
};

/**
 * 删除本地缓存中的搜索历史关键字
 */
export const removeLocalHistories = () => {
  localStorage.removeItem(SEARCH_HIS_KEY);
};
